package main

import (
	"log"
	"os"

	"github.com/go-xorm/xorm"
	_ "github.com/mattn/go-sqlite3"
)

type Account struct {
	Id      int64
	Name    string `xorm:unique`
	Balance float64
}

// BeforeInsert xorm的插入前钩子函数
func (a *Account) BeforeInsert() {
	log.Println("Before insert:", a.Name)
}

// AfterInsert xorm的插入后钩子函数
func (a *Account) AfterInsert() {
	log.Println("After instert:", a.Name)
}

var x *xorm.Engine

func init() {
	var err error
	x, err = xorm.NewEngine("sqlite3", "./blank.db")
	if err != nil {
		log.Printf("Fail to create engine:%v", err)
	}
	err = x.Sync(new(Account))
	if err != nil {
		log.Printf("Fail to sync databa:%v", err)
	}

	//记录日志
	f, err := os.Create("sql.log")
	if err != nil {
		log.Fatalln("Fail to create log file:", err)
	}
	x.SetLogger(xorm.NewSimpleLogger(f))
	x.ShowSQL(true)
	//开启LRU缓存
	cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
	x.SetDefaultCacher(cacher)
}

func getAccountCount() (int64, error) {
	return x.Count(&Account{})
}

func newAccount(name string, balance float64) error {
	_, err := x.Insert(&Account{Name: name, Balance: balance})
	return err
}
